from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class Objective(models.Model):
    """目标模型 - OKR中的O"""
    title = models.CharField(max_length=200, verbose_name="目标标题")
    description = models.TextField(blank=True, verbose_name="目标描述")
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="objectives", verbose_name="负责人")
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, 
                             related_name='children', verbose_name="父级目标")
    level = models.CharField(max_length=20, choices=[
        ('department', '部门级'),
        ('team', '团队级'),
        ('personal', '个人级')
    ], default='personal', verbose_name="目标层级")
    start_date = models.DateField(default=timezone.now, verbose_name="开始日期")
    end_date = models.DateField(verbose_name="结束日期")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    status = models.CharField(
        max_length=20, 
        choices=[
            ('not_started', '未开始'),
            ('in_progress', '进行中'),
            ('completed', '已完成'),
            ('cancelled', '已取消')
        ],
        default='not_started',
        verbose_name="状态"
    )
    
    def __str__(self):
        return self.title
    
    @property
    def breadcrumb(self):
        """获取目标的层级路径"""
        path = [self]
        current = self
        while current.parent:
            path.insert(0, current.parent)
            current = current.parent
        return path
    
    @property
    def children_summary(self):
        """获取子目标的摘要信息"""
        return self.children.all().values('id', 'title', 'status')
    
    class Meta:
        verbose_name = "目标"
        verbose_name_plural = "目标"
        ordering = ['-created_at']

class KeyResult(models.Model):
    """关键结果模型 - OKR中的KR"""
    objective = models.ForeignKey(Objective, on_delete=models.CASCADE, related_name="key_results", verbose_name="所属目标")
    title = models.CharField(max_length=200, verbose_name="关键结果标题")
    description = models.TextField(blank=True, verbose_name="关键结果描述")
    assignee = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="assigned_key_results", verbose_name="负责人")
    progress = models.IntegerField(default=0, verbose_name="进度百分比")  # 0-100的整数
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    status = models.CharField(
        max_length=20, 
        choices=[
            ('not_started', '未开始'),
            ('in_progress', '进行中'),
            ('completed', '已完成'),
            ('at_risk', '有风险')
        ],
        default='not_started',
        verbose_name="状态"
    )
    
    def __str__(self):
        return self.title
    
    class Meta:
        verbose_name = "关键结果"
        verbose_name_plural = "关键结果"
        ordering = ['objective', '-created_at']

class CheckIn(models.Model):
    """进度检查模型 - 记录KR的定期更新"""
    key_result = models.ForeignKey(KeyResult, on_delete=models.CASCADE, related_name="check_ins", verbose_name="关键结果")
    date = models.DateField(default=timezone.now, verbose_name="检查日期")
    previous_progress = models.IntegerField(verbose_name="上次进度")
    current_progress = models.IntegerField(verbose_name="当前进度")
    notes = models.TextField(blank=True, verbose_name="备注")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_check_ins", verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    def __str__(self):
        return f"{self.key_result.title} - {self.date}"
    
    class Meta:
        verbose_name = "进度检查"
        verbose_name_plural = "进度检查"
        ordering = ['-date']

class Team(models.Model):
    """团队模型"""
    name = models.CharField(max_length=100, verbose_name="团队名称")
    description = models.TextField(blank=True, verbose_name="团队描述")
    leader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="leading_teams", verbose_name="团队负责人")
    members = models.ManyToManyField(User, related_name="teams", verbose_name="团队成员")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = "团队"
        verbose_name_plural = "团队"
        ordering = ['name']

class Comment(models.Model):
    """评论模型 - 可以关联到目标或关键结果"""
    content = models.TextField(verbose_name="评论内容")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments", verbose_name="评论人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    # 以下两个字段只能填写一个，代表评论关联的对象
    objective = models.ForeignKey(Objective, on_delete=models.CASCADE, null=True, blank=True, related_name="comments", verbose_name="关联目标")
    key_result = models.ForeignKey(KeyResult, on_delete=models.CASCADE, null=True, blank=True, related_name="comments", verbose_name="关联关键结果")
    
    def __str__(self):
        return f"{self.created_by.username}的评论 - {self.created_at.strftime('%Y-%m-%d')}"
    
    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"
        ordering = ['-created_at']
